﻿using System.Collections.Generic;
using System.IO;
using Pandora;
using PandoraEditor;
using UnityEngine;

namespace NeatlyEditor
{
    public static class NeatlyLocalServerHelper
    {
        public static void AssetToLocalServer()
        {
            var setting = BuildSetting.LocalServerSetting;
            var versionName = CommandParam.Develop ? $"/{UserSetting.VersionSetting.version_name}" : "";
#if UNITY_IPHONE || UNITY_IOS
            string outputFolder = Path.Combine($"{setting.path_mac_asset}{versionName}", NeatlyConfig.NAME_SYSTEM_PLATFORM);
#else
            string outputFolder = Path.Combine($"{setting.path_asset}{versionName}", NeatlyConfig.NAME_SYSTEM_PLATFORM);
#endif
            PdrFileUtil.DeleteFile(Path.Combine(outputFolder, NeatlyConfig.FILE_TXT_VERSION));
            PdrFileUtil.CopyDirectoryOverride(NeatlyEditorConfig.PATH_EXPORT_BUNDLE, outputFolder);
            Debug.Log("Copy Asset To Local Server complete.");
        }

        public static void PackageWin64ToLocalServer()
        {
            var localServerSetting = BuildSetting.LocalServerSetting;
            var versionSetting = UserSetting.VersionSetting;
            string outputFolder = Path.Combine($"{localServerSetting.path_package_svn}/{versionSetting.version_name}", NeatlyConfig.NAME_SYSTEM_PLATFORM);
            PdrFileUtil.DeleteDirectory(outputFolder);
            PdrFileUtil.CopyDirectory(NeatlyEditorConfig.PATH_WIN64, outputFolder);
            Application.OpenURL(outputFolder);
            Debug.Log("Copy Package Win64 To Local Server complete.");
        }

        public static void PackageAndroidToLocalServer()
        {
            string packSuffix = CommandParam.Develop ? "debug" : "release";
            string bundleSuffix = CommandParam.UseAab ? "aab" : "apk";
            string bundleFolder = CommandParam.UseAab ? "bundle" : "apk";
            string bundlePath = Path.Combine(NeatlyEditorConfig.PATH_ANDROID_PROJECT, $"launcher/build/outputs/{bundleFolder}", packSuffix, $"launcher-{packSuffix}.{bundleSuffix}");
            var setting = BuildSetting.LocalServerSetting;
            var remoteFileName = $"{BuildSetting.ProjectBuildSetting.product_name}_{CommandParam.PatchCode}_{packSuffix}.{bundleSuffix}";
            PdrFileUtil.CopyFile(bundlePath, $"{setting.path_package_server}/{NeatlyConfig.NAME_SYSTEM_PLATFORM}/{remoteFileName}");
            Application.OpenURL(setting.path_package_server);
            Debug.Log("Copy Package Android To Local Server complete.");
            var dict = new Dictionary<string, string>();
            dict.Add(bundleSuffix, $"{setting.path_asset_url}/package/android/{remoteFileName}");

            var version = $"{CommandParam.Version}.{CommandParam.PatchCode}";
            DingDingHelper.PostCards($"{BuildSetting.ProjectBuildSetting.product_name} 安卓包好了 ({version})", dict);
        }

        public static void PackageIOSIpaToLocalServer()
        {
            var setting = BuildSetting.LocalServerSetting;
            //adhoc包
            var fileName = $"{BuildSetting.ProjectBuildSetting.product_name}_{CommandParam.PatchCode}_adhoc.ipa";
            var plistFileName = $"{BuildSetting.ProjectBuildSetting.product_name}_{CommandParam.PatchCode}_adhoc.plist";
            var adhocIpaPath = $"{NeatlyEditorConfig.PATH_IOS_PROJECT}/build/tmp/adhoc/{RemoveSpaces(BuildSetting.ProjectBuildSetting.product_name)}.ipa";
            PdrFileUtil.CopyFile(adhocIpaPath, $"{setting.path_mac_package_server}/{fileName}");
            Application.OpenURL(setting.path_mac_package_server);
            Debug.Log("Copy Package IOS Adhoc To Local Server complete.");
            var ipaDownloadUrl = $"{setting.path_asset_url}/package/ios/{fileName}";
            var installPlistUrl = $"{setting.path_asset_url}/package/ios/{plistFileName}";
            var plistTemplateFile = $"{NeatlyEditorConfig.PATH_IOS_PROJECT}/../overlay/install.plist";
            var manifestText = File.ReadAllText(plistTemplateFile);
            manifestText = manifestText.Replace("${IPA_URL}", ipaDownloadUrl)
                .Replace("${BUNDLE_IDENTIFIER}", CommandParam.BundleIdentifier)
                .Replace("${VERSION_CODE}", CommandParam.Version)
                .Replace("${PRODUCT_NAME}", CommandParam.ProductName);
            File.WriteAllText($"{setting.path_mac_package_server}/{plistFileName}", manifestText);
            var dict = new Dictionary<string, string>()
            {
                { "在线安装", $"itms-services://?action=download-manifest&url={installPlistUrl}" },
                { "adhoc ipa下载", ipaDownloadUrl },
            };
            //dis包
            if (CommandParam.ExportDis)
            {
                var disIpaPath = $"{NeatlyEditorConfig.PATH_IOS_PROJECT}/build/tmp/dis/{RemoveSpaces(BuildSetting.ProjectBuildSetting.product_name)}.ipa";
                fileName = $"{BuildSetting.ProjectBuildSetting.product_name}_{CommandParam.PatchCode}_dis.ipa";
                ipaDownloadUrl = $"{setting.path_asset_url}/package/ios/{fileName}";
                PdrFileUtil.CopyFile(disIpaPath, $"{setting.path_mac_package_server}/{fileName}");
                dict.Add("dis ipa下载", ipaDownloadUrl);
            }

            var version = $"{CommandParam.Version}.{CommandParam.PatchCode}";
            DingDingHelper.PostCards($"{BuildSetting.ProjectBuildSetting.product_name} ios包好了 ({version})", dict);
        }

        public static void PackageWeiXinToLocalServer(string localPath)
        {
            var setting = BuildSetting.LocalServerSetting;
            var exportFoldName = $"wxproj_{CommandParam.PatchCode}";
            var dstUrl = $"{setting.path_package_server}/{NeatlyConfig.NAME_SYSTEM_PLATFORM}/{exportFoldName}";
            var webUrl = $"{setting.path_asset_url}/package/webgl/{exportFoldName}/webgl/index.html";
            PdrFileUtil.CopyDirectory(localPath, dstUrl);
            var dict = new Dictionary<string, string>()
            {
                { "在线地址", webUrl },
            };

            var version = $"{CommandParam.Version}.{CommandParam.PatchCode}";
            DingDingHelper.PostCards($"{BuildSetting.ProjectBuildSetting.product_name} WeiXin包好了 ({version})", dict);
        }

        static string RemoveSpaces(string input)
        {
            return input.Replace(" ", "");
        }
    }
}